// src/pages/catering/goodsList/popGoodsList/goodsList/goodsList.js
import getIn from '../../../../../../yali-sdk/utils/getIn';
import { updateVariableParams, getImagePath, showFail, showSuccess } from '../../../../../config/common';
import { SUCCESS } from '../../../../../../yali-sdk/utils/success';
import { FAIL } from '../../../../../../yali-sdk/utils/fail';
import goodsListQuery from '../../../../../../yali-sdk/business/catering/goodsListQuery';
import getGoodsCartQuery from '../../../../../../yali-sdk/business/catering/getGoodsCartQuery';
import cartDetailQuery from '../../../../../../yali-sdk/business/catering/cartDetailQuery';
import cartEmptyQuery from '../../../../../../yali-sdk/business/catering/cartEmptyQuery';
import fetchShopDetail from '../../../../../../yali-sdk/business/shop/fetchShopDetail';
import productCateList from '../../../../../../yali-sdk/business/catering/productCateList';
import { CATERING_CREAT_ORDER, COUPON_LIST_PATH, CATERING_PRODUCT_DETAIL, POP_GOODS_LIST } from '../../../../../pages/pathUrl';
import { updateNum, payDescText } from '../../../../../../yali-sdk/business/catering/constrants';
const windowHeight = wx.getSystemInfoSync().windowHeight;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    cateList: [],
    categoryfirstid: 0, // 一级分类id
    categorysecondid: 0, // 二级分类id
    cateText: '全部产品', // 产品列表title
    menuShow: false,
    animationData: {},
    productList:[],
    showAttr: false, // 选择属性弹窗
    selectPro: {}, // 有属性选择的产品（弹出属性弹窗后的数据）
    totalPrice: 0,// 总价格
    totalCount: 0, // 总商品数
    carArray: [],
    minPrice: 0,//起送价格
    payDesc: '去结算', // 右下角结算文字
    deliveryPrice: 0,//配送費
    fold: false,// 购物车开关
    params: {
      page: 1,
      rows: 10,
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    const shop_detail = JSON.parse(options.shop_detail);
    const token = getIn(getApp(), ['globalData', 'token']);
    this.setData({ shop_detail });
    this.dataCateList(shop_detail, token);
    if (shop_detail.template == 3) {
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#000',
      });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.fetchData();
    this.fetchCart(this.data.shop_detail, this.data.token);
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
    const page = 1;
    const params = updateVariableParams(this.data.params, { page });
    this.data.params = params;
    this.fetchData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
    const { total, productList } = this.data;
    if (productList.length < total) {
      // 界面加载完, 且还有下一页的情况。
      const pages = getIn(this.data, ['params', 'page']) || 1;
      const params = updateVariableParams(this.data.params, { page: pages + 1 });
      this.data.params = params;
      this.fetchData();
    }
  },
  // 产品分类
  dataCateList(shop_detail, token) {
    token = token || getIn(getApp(), ['globalData', 'token']);
    global.ActionDispatcher.execute(productCateList, { token, shop_id: shop_detail.id }, (code, res) => {
      if(code == SUCCESS) {
        let cateList = getIn(res.data, ['list']);
        cateList = cateList.map((x) => {
          x._child && x._child.unshift({ id: 0, cate_name: '全部' });
          return x
        });
        cateList.unshift({ id: 0, cate_name: '全部' });
        this.setData({ cateList });
      }
    })
  },
  // 访问列表数据
  fetchData(param) {
    const token = getIn(getApp(), ['globalData', 'token']);
    const params = { token, shop_id: this.data.shop_detail.id, ...this.data.params, ...param };
    global.ActionDispatcher.execute(goodsListQuery, params, (code, res) => {
      if (code == SUCCESS) {
        wx.stopPullDownRefresh();
        wx.hideLoading();
        let list = getIn(res.data, ['list']);
        const total = getIn(res.data, ['total']);
        list = params.page == 1 ? list : this.data.productList.concat(list);
        this.setData({ productList: list, total })
      } else if (code == FAIL) {
        wx.stopPullDownRefresh();
        wx.hideLoading();
      }
    });
  },
  // 产品名称搜索
  searchShop() {
    this.fetchData({ title:this.data.title })
  },
  // 输入产品名称
  onChange(e) {
    const title = getIn(e.detail, ['value']);
    this.setData({ title });
  },
  // 选择分类
  onSelect(e) {
    const categoryfirstid = getIn(e.currentTarget.dataset, ['categoryfirstid']);
    const categorysecondid = getIn(e.currentTarget.dataset, ['categorysecondid']);
    const name = getIn(e.currentTarget.dataset, ['name']);
    if (categoryfirstid != undefined) {
      const cateFirst = this.data.cateList.find(x => x.id == categoryfirstid);
      const cateSecondList = getIn(cateFirst, ['_child']);
      if (cateSecondList && cateSecondList.length > 0) {
        this.showModal(cateSecondList);
        if (categoryfirstid != this.data.categoryfirstid) {
          this.setData({ categorysecondid: 0 });
        }
      } else {
        this.hideModal();
      }
      this.fetchData({ cate_id: categoryfirstid });
      this.setData({ categoryfirstid, cateText: name });
    } else if (categorysecondid != undefined) {
      if (categorysecondid != 0) {
        this.setData({ cateText: `${this.data.cateText} - ${name}` });
      }
      this.fetchData({ cate_id: categorysecondid });
      this.setData({ categorysecondid });
      this.hideModal();
    }
  },
  // 购物车数据
  fetchCart(shop_detail, token) {
    token = token || getIn(getApp(), ['globalData', 'token']);
    global.ActionDispatcher.execute(cartDetailQuery, { token, shop_id: shop_detail.id }, (code, res) => {
      if (code == SUCCESS) {
        const carArray = getIn(res.data, ['list']) || [];
        const totalPrice = getIn(res.data, ['total_price']) || 0;
        const totalCount = getIn(res.data, ['total_num']) || 0;
        const payDesc = payDescText(totalPrice, this.data.minPrice);
        this.setData({ carArray, totalPrice: totalPrice, totalCount, payDesc });
      } if (code == FAIL) {
        const payDesc = payDescText(this.data.totalPrice, this.data.minPrice);
        this.setData({ payDesc });
      }
    });
  },
  //清空回收站
  clearCart(e) {
    const token = getIn(getApp(), ['globalData', 'token']);
    const shop_id = getIn(this.data, ['shop_detail', 'id']);
    global.ActionDispatcher.execute(cartEmptyQuery, { token, shop_id }, (code, res) => {
      if (code == SUCCESS) {
        this.fetchData(this.data.shop_detail);
        this.fetchCart(this.data.shop_detail);
        this.setData({ fold: false });
        showSuccess('操作成功');
      } else if (code == FAIL) {
        showFail('操作失败');
      }
    })
  },
  //修改产品购物车数量
  modifiesCart(e) {
    const { productList, carArray } = this.data;
    const id = e.currentTarget.id || e.detail.id;
    const num = getIn(e.currentTarget.dataset, ['num']) || e.detail.num || 0;
    const token = getIn(getApp(), ['globalData', 'token']);
    const shop_id = getIn(this.data.shop_detail, ['id']);
    const group_attr = getIn(e.detail, ['group_attr']);
    const callback = getIn(e.detail, ['callback']);
    const params = group_attr ? { token, shop_id, product_id: id, num: Number(num), group_attr } : { token, shop_id, product_id: id, num: Number(num) }; 
    const obj = { ...updateNum([{ product_list: productList }], Number(num), id, group_attr) };
    this.setData({ productList: obj.product[0].product_list, selectPro: obj.selectPro });
    global.ActionDispatcher.execute(getGoodsCartQuery, params, (code, res) => {
      if (code == SUCCESS) {
        const carArray = getIn(res.data, ['list']);
        const totalPrice = getIn(res.data, ['total_price']);
        const totalCount = getIn(res.data, ['total_num']);
        const payDesc = payDescText(totalPrice, this.data.minPrice);
        if (totalCount == 0) {
          this.setData({ fold: false });
        }
        this.setData({ carArray, totalPrice, totalCount });
      } else if (code == FAIL) {
        showFail(res.msg);
        if (Number(res.code) == -101) {
          const obj = { ...updateNum([{ product_list: productList }], 0, id, group_attr) };
          this.setData({ productList: obj.product[0].product_list, selectPro: obj.selectPro });
        } else {
          const reset_num = getIn(res.data, ['num']);
          const reset_id = getIn(res.data, ['id']);
          const reset_attr_group_id = getIn(res.data, ['attr_group_id']);
          const obj = { ...updateNum([{ product_list: productList }], Number(reset_num), id, reset_attr_group_id) }
          this.setData({ productList: obj.product[0].product_list, selectPro: obj.selectPro });
        }
      }
    });
  },
  //结算
  pay() {
    if (this.data.totalPrice == 0 || this.data.totalPrice < this.data.minPrice) {
      return;
    }
    const color = getIn(this.data.shop_detail, ['color']);
    const template = getIn(this.data.shop_detail, ['template']);
    const shop_id = getIn(this.data.shop_detail, ['id']);
    const queryString = `color=${color}&shop_id=${shop_id}&template=${template}`;
    global.navigateHelper && global.navigateHelper.navigateTo({ pathname: CATERING_CREAT_ORDER, queryString });
  },
  //弹起购物车
  toggleList() {
    if (this.data.totalCount > 0) {
      this.setData({ fold: true });
    }
  },
  // 关闭购物车
  hideCartCallBack(e) {
    this.setData({ fold: e.detail.fold });
  },
  // 选择规格弹出窗
  selectAttr(e) {
    const { productList } = this.data;
    const cate_id = getIn(e.currentTarget, ['dataset', 'cate_id']);
    const id = getIn(e.currentTarget, ['id']);
    const selectCate = productList.find(x => x.id == cate_id);
    const selectPro = selectCate && selectCate.product_list.find(t => t.id == id);
    this.setData({ showAttr: true, selectPro });
  },
  // 关闭属性框回调
  hideAttrBoxCallBack(e) {
    this.setData({ showAttr: e.detail.showAttr, selectPro: {} });
  },
  // 跳转详细页
  toDetail(e) {
    const id = getIn(e.currentTarget, ['id']);
    const { shop_detail } = this.data;
    let queryString = '';
    if (shop_detail.template == 3) {
      queryString = `id=${id}&color=#000&shop_id=${shop_detail.id}&template=${shop_detail.template}`;
    } else {
      queryString = `id=${id}&color=${shop_detail.color}&shop_id=${shop_detail.id}template=${shop_detail.template}`;
    }
    global.navigateHelper && global.navigateHelper.navigateTo({ pathname: CATERING_PRODUCT_DETAIL, queryString });
  },
  /**弹出分类弹窗**/
  showModal(cateSecondList) {
    this.timers && clearTimeout(this.timers);
    const animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear',
      delay: 0,
    });
    this.animation = animation;
    animation.translateY(-windowHeight * 0.5).step();
    this.setData({ animationData: animation.export(), menuShow: true, cateSecondList });
    this.times = setTimeout(() => {
      animation.translateY(0).step();
      this.setData({
        animationData: animation.export()
      });
    }, 200);
  },
  // 取消弹出框
  hideModal() {
    this.timers && clearTimeout(this.timers);
    const animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear',
      delay: 0,
    });
    this.animation = animation;
    animation.translateY(-windowHeight * 0.5).step();
    this.setData({ animationData: animation.export() });
    this.times = setTimeout(() => {
      animation.translateY(0).step();
      this.setData({
        animationData: animation.export(),
        menuShow: false
      });
    }, 200);
  },
})